"use client"

import React, { useState } from "react"
import { Box, Paper, Tabs, Tab, IconButton, Tooltip, Typography, Snackbar, Alert } from "@mui/material"
import { ContentCopy as CopyIcon, Visibility as PreviewIcon, Code as CodeIcon } from "@mui/icons-material"

interface HtmlPreviewProps {
	htmlContent: string
	title?: string
}

export default function HtmlPreview({ htmlContent, title = "HTML 预览" }: HtmlPreviewProps) {
	const [activeTab, setActiveTab] = useState(0)
	const [copySuccess, setCopySuccess] = useState(false)

	// 提取 HTML 内容（去除可能的 markdown 代码块标记）
	const cleanHtmlContent = htmlContent
		.replace(/```html\n?/g, "")
		.replace(/```\n?/g, "")
		.trim()

	const handleTabChange = (_: React.SyntheticEvent, newValue: number) => {
		setActiveTab(newValue)
	}

	const handleCopyCode = async () => {
		try {
			await navigator.clipboard.writeText(cleanHtmlContent)
			setCopySuccess(true)
		} catch (err) {
			console.error("复制失败:", err)
		}
	}

	const handleCloseCopySuccess = () => {
		setCopySuccess(false)
	}

	return (
		<Box sx={{ width: "100%", mt: 2 }}>
			<Paper
				elevation={1}
				sx={{
					border: "1px solid",
					borderColor: "grey.300",
					borderRadius: 2,
					overflow: "hidden"
				}}
			>
				{/* 标题栏和操作按钮 */}
				<Box
					sx={{
						display: "flex",
						alignItems: "center",
						justifyContent: "space-between",
						px: 2,
						py: 1,
						bgcolor: "grey.50",
						borderBottom: "1px solid",
						borderColor: "grey.200"
					}}
				>
					<Typography variant='subtitle2' color='text.secondary'>
						{title}
					</Typography>
					<Tooltip title='复制 HTML 代码'>
						<IconButton size='small' onClick={handleCopyCode} sx={{ color: "primary.main" }}>
							<CopyIcon fontSize='small' />
						</IconButton>
					</Tooltip>
				</Box>

				{/* 标签页 */}
				<Tabs
					value={activeTab}
					onChange={handleTabChange}
					sx={{
						borderBottom: "1px solid",
						borderColor: "grey.200",
						minHeight: 40,
						"& .MuiTab-root": {
							minHeight: 40,
							textTransform: "none",
							fontSize: "0.875rem"
						}
					}}
				>
					<Tab icon={<PreviewIcon fontSize='small' />} label='预览' iconPosition='start' />
					<Tab icon={<CodeIcon fontSize='small' />} label='代码' iconPosition='start' />
				</Tabs>

				{/* 内容区域 */}
				<Box sx={{ p: 2 }}>
					{activeTab === 0 && (
						// 预览模式
						<Box
							sx={{
								minHeight: 200,
								border: "1px dashed",
								borderColor: "grey.300",
								borderRadius: 1,
								p: 2,
								bgcolor: "white",
								"& *": {
									maxWidth: "100%"
								}
							}}
							dangerouslySetInnerHTML={{ __html: cleanHtmlContent }}
						/>
					)}

					{activeTab === 1 && (
						// 代码模式
						<Box
							component='pre'
							sx={{
								bgcolor: "grey.900",
								color: "grey.100",
								p: 2,
								borderRadius: 1,
								fontSize: "0.875rem",
								fontFamily: 'Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
								overflow: "auto",
								maxHeight: 400,
								margin: 0,
								whiteSpace: "pre-wrap",
								wordBreak: "break-all"
							}}
						>
							{cleanHtmlContent}
						</Box>
					)}
				</Box>
			</Paper>

			{/* 复制成功提示 */}
			<Snackbar open={copySuccess} autoHideDuration={2000} onClose={handleCloseCopySuccess} anchorOrigin={{ vertical: "top", horizontal: "center" }}>
				<Alert onClose={handleCloseCopySuccess} severity='success' variant='filled' sx={{ fontSize: "0.875rem" }}>
					HTML 代码已复制到剪贴板！
				</Alert>
			</Snackbar>
		</Box>
	)
}
